package zpy.servlet.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import zpy.servlet.pojo.ErrorMessage;

/**
 * Servlet implementation class FileUploadServlet
 */
@WebServlet("/fileUploadServlet")
@MultipartConfig(
        fileSizeThreshold = 1024 * 10,    // 10KB
        maxFileSize = 1024 * 1024 * 10,   // 10MB
        maxRequestSize = 1024 * 1024 * 1024 // 1GB
)
public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    public void init() throws ServletException {
        // 创建临时目录
        String tempFilePath = getServletContext().getInitParameter("file_download_temp_path");
        File tempFile = new File(tempFilePath);
        if (!tempFile.exists()) {
            tempFile.mkdirs();
        }
    }

    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileUploadServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 检查是否为multipart内容
        if (!request.getContentType().startsWith("multipart/")) {
            ErrorMessage message = new ErrorMessage("文件上传错误",
                    "文件上传enctype错误",
                    "请将form标签的method设置为post，将enctype设置为multipart/form-data",
                    request.getRequestURL().toString());
            request.setAttribute("message", message);
            getServletContext().getRequestDispatcher("/WEB-INF/jsp/public/error.jsp")
                    .forward(request, response);
            return;
        }

        try {
            // 获取所有part
            Collection<Part> parts = request.getParts();

            response.setContentType("text/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();

            // 处理每个part
            for (Part part : parts) {
                String fieldName = part.getName();

                if (part.getSubmittedFileName() == null) {
                    // 普通表单字段
                    String fieldValue = request.getParameter(fieldName);
                    writer.println("普通字段：" + fieldName + "----->>>" + fieldValue);
                    System.out.println("普通字段：" + fieldName + "----->>>" + fieldValue);
                } else {
                    // 文件字段
                    String fileName = part.getSubmittedFileName();
                    System.out.println(fileName);

                    if (fileName == null || fileName.isEmpty()) {
                        continue;
                    }

                    // 获取文件名（去除路径）
                    int pos = fileName.lastIndexOf("\\");
                    if (pos != -1) {
                        fileName = fileName.substring(pos + 1);
                    }

                    // 获取保存路径
                    String tempFilePath = getServletContext().getInitParameter("file_download_temp_path");
                    File filePath = new File(tempFilePath);
                    File file = new File(filePath, fileName);

                    // 保存文件
                    part.write(file.getAbsolutePath());
                    String contentType = part.getContentType();
                    writer.println("文件字段，文件名:" + fileName + "----->>>文件MIME类型:" + contentType);
                }
            }
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
            ErrorMessage message = new ErrorMessage("文件上传错误",
                    "文件内容解析出错",
                    "与开发人员联系",
                    request.getRequestURL().toString());
            request.setAttribute("message", message);
            getServletContext().getRequestDispatcher("/WEB-INF/jsp/public/error.jsp")
                    .forward(request, response);
            return;
        }
    }
}
